import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 修改密码
/// 此页面仅用于登录前修改密码
class ChangePasswordPage extends ConsumerStatefulWidget {
  const ChangePasswordPage({super.key});

  @override
  ConsumerState<ChangePasswordPage> createState() => _ChangePasswordPageState();
}

class _ChangePasswordPageState extends ConsumerState<ChangePasswordPage> {
  final _formKey = GlobalKey<FormState>();
  final _oldPasswordController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final textColor = Colors.black;

  /// 输入框间距
  final double _inputMargin = 12;

  /// 修改设备密码
  _changeDevicePassword() async {
    final changePasswordData = {
      'oldPassword': _oldPasswordController.text,
      'newPassword': _passwordController.text,
      'imei': SpUtil.getString('tempLoginImei'),
    };
    ToastUtils.showLoading();
    var res =
        await post<BaseResp, BaseResp>('/app/user/device/password', data: changePasswordData, decodeType: BaseResp());
    res.when(success: (BaseResp resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        ToastUtils.showToast('修改密码成功');
        SpUtil.remove('needChangePassword');
        SpUtil.remove('tempLoginImei');
        // 延迟1秒跳转
        Future.delayed(const Duration(seconds: 1), () {
          context.go('/');
        });
      } else {
        ToastUtils.showToast(resp.msg ?? '修改失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('修改密码失败 code: $code msg: $msg');
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // 返回按钮的颜色
        iconTheme: const IconThemeData(color: Colors.black),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 标题
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(
                left: 20,
              ),
              child: const Text(
                '修改密码',
                style: TextStyle(
                  fontSize: 24,
                ),
              ),
            ),
            // 提示
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(
                left: 20,
              ),
              child: Text(
                '当前密码较弱，请修改密码后再使用',
                style: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
              ),
            ),
            const SizedBox(
              height: 60,
            ),
            // 表单
            Container(
              margin: const EdgeInsets.only(left: 20, right: 20),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    // 旧密码
                    TextFormField(
                      controller: _oldPasswordController,
                      obscureText: true,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请输入旧密码",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        // 调整内边距
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入旧密码';
                        }
                        return null;
                      },
                    ),
                    SizedBox(
                      height: _inputMargin,
                    ),
                    TextFormField(
                      controller: _passwordController,
                      obscureText: true,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请输入新密码",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        // 调整内边距
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入新密码';
                        }
                        return null;
                      },
                    ),
                    SizedBox(
                      height: _inputMargin,
                    ),
                    TextFormField(
                      controller: _confirmPasswordController,
                      obscureText: true,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请确认新密码",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        // 调整内边距
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请确认新密码';
                        }
                        if (value != _passwordController.text) {
                          return '两次输入的密码不一致';
                        }
                        return null;
                      },
                    ),
                    // 密码强度提示
                    Container(
                      alignment: Alignment.topLeft,
                      margin: const EdgeInsets.only(left: 20, top: 10),
                      child: Text(
                        '8-16位英文字母、数字、字符组合，不能是纯数字',
                        style: TextStyle(
                          fontSize: 12,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    // 登录按钮
                    SizedBox(
                      width: double.infinity,
                      height: 50,
                      child: ElevatedButton(
                        onPressed: () {
                          // 校验表单
                          if (_formKey.currentState!.validate()) {
                            // 验证通过提交数据
                            _changeDevicePassword();
                          }
                        },
                        style: ButtonStyle(
                          shape: MaterialStateProperty.all(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(32),
                            ),
                          ),
                          backgroundColor: MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
                        ),
                        child: const Text(
                          "确定",
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
